﻿using System;
using DevExpress.XtraEditors;
using System.Linq;
using System.Configuration;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Windows.Forms;

namespace KasaTakip
{
    public partial class frmMain : XtraForm
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void kasaAlımıToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmKasaAlimi frm = new frmKasaAlimi())
            {
                frm.IslemTarihi = dteIslemTarihi.Value.ToSmallDate();
                frm.ShowDialog();
            }
        }

        private void anaKasaFöyüToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmTransfer trn = new frmTransfer())
            {
                trn.IslemTarihi = dteIslemTarihi.Value.ToSmallDate();
                trn.ShowDialog();
            }
        }

        private void şubeyeParaGönderimiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmMagazaGonderim frm = new frmMagazaGonderim())
            {
                frm.IslemTarihi = dteIslemTarihi.Value.ToSmallDate();
                frm.ShowDialog(this);
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Icon = Properties.Resources.ikon;
            dteIslemTarihi.Value = DateTime.Now.ToSmallDate();
            KapanisKontrol(dteIslemTarihi.Value);

            if (Program.AktifDepoNo == 99)
            {
                label2.Visible = true;
                Program.AdminMode = true;
                cmbMagaza.Visible = true;
                cmbMagaza.Items.AddRange(Program.Db.Magazalar.ToArray());
            }



            if (File.Exists(Application.StartupPath + "\\doviz.xml"))
            {
                dovizOku(Application.StartupPath + "\\doviz.xml");
            }
        }

        private void KapanisKontrol(DateTime secilenTarih)
        {
            lblUyari.Visible = false;
            timer1.Enabled = false;
            DateTime onceki = new DateTime(secilenTarih.Year, secilenTarih.Month, secilenTarih.Day).AddDays(-1);
            using (KasaEntity ent = new KasaEntity())
            {
                var sonKapanis = ent.Kapanislar.Where(x => x.MagazaNo == Program.AktifDepoNo && x.Tarih == onceki).FirstOrDefault();
                if (sonKapanis == null)
                {
                    timer1.Enabled = true;
                }
            }
        }

        private void kasaÖzetRaporuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int MagazaNo = Program.AktifDepoNo;
            DateTime bugun = dteIslemTarihi.Value.ToSmallDate();
            DataTable dt = new DataTable();
            dt.Columns.Add("Bilgi", typeof(string));

            using (KasaEntity ent = new KasaEntity())
            {
                var closures = (from h in ent.KasaKapanislari
                                join k in ent.Kasalar on h.KasaID equals k.ID
                                join ks in ent.Kasiyerler on h.KasiyerID equals ks.ID
                                where h.MagazaID == MagazaNo && h.Tarih == bugun
                                select new { ClosureID = h.ID, KasaNo = k.No, KasiyerAdi = ks.KasiyerAdi, h.KasaFarki, h.NakitToplam, h.KrediToplam, h.HarcamalarToplam, h.MasrafFaturalarToplam }).ToList();

                foreach (var c in closures)
                {
                    dt.Columns.Add("Kasa:" + c.KasaNo + " Kasiyer:" + c.KasiyerAdi, typeof(double));
                }

                int row = -1;
                for (int i = 0; i < 100; i++)
                {
                    dt.Rows.Add();
                }

                var bankalar = ent.Bankalar.ToList();
                var masraflar = ent.MasrafTanimlari.Where(x => x.MagazaNo == MagazaNo).ToList();
                var paralar = ent.ParaBirimleri.ToList();

                foreach (var c in closures)
                {
                    row = 0;
                    string colName = "Kasa:" + c.KasaNo + " Kasiyer:" + c.KasiyerAdi;
                    #region Nakit Hareketleri
                    dt.Rows[row]["Bilgi"] = "---Nakit Detayları---";
                    var nakit = ent.NakitHareketleri.Where(x => x.ClosureID == c.ClosureID).ToList();
                    foreach (var n in paralar.OrderBy(x => x.Carpan))
                    {
                        row++;
                        dt.Rows[row]["Bilgi"] = n.ParaCinsi;
                        dt.Rows[row][colName] = nakit.Where(x => x.ParaCinsi == n.ParaCinsi).Select(x => x.Tutar).Sum();
                    }
                    row++;
                    dt.Rows[row]["Bilgi"] = "Nakit Toplam:";
                    dt.Rows[row][colName] = nakit.Select(x => x.Tutar).Sum();
                    #endregion

                    #region Banka Hareketleri
                    row++;
                    dt.Rows[row]["Bilgi"] = "---Banka Detayları---";
                    var banka = ent.BankaHareketleri.Where(x => x.ClosureID == c.ClosureID).ToList();
                    foreach (var b in bankalar)
                    {
                        row++;
                        dt.Rows[row]["Bilgi"] = b.Aciklama;
                        dt.Rows[row][colName] = banka.Where(x => x.BankaID == b.ID).Select(x => x.Tutar).Sum();
                    }
                    row++;
                    dt.Rows[row]["Bilgi"] = "Banka Toplam:";
                    dt.Rows[row][colName] = banka.Select(x => x.Tutar).Sum();
                    #endregion

                    #region Dahili Harcamalar
                    row++;
                    dt.Rows[row]["Bilgi"] = "---Dahili Harcamalar---";
                    var masrafFaturalari = ent.MasrafFaturalari.Where(x => x.ClosureID == c.ClosureID).ToArray();
                    foreach (var m in masraflar)
                    {
                        row++;
                        dt.Rows[row]["Bilgi"] = m.Adi;
                        dt.Rows[row][colName] = masrafFaturalari.Where(x => x.MasrafID == m.ID).Select(x => x.Tutar).Sum();
                    }
                    row++;
                    dt.Rows[row]["Bilgi"] = "Dahili Harcamalar Toplam:";
                    dt.Rows[row][colName] = masrafFaturalari.Select(x => x.Tutar).Sum();
                    #endregion

                    #region Serbest Masraf
                    row++;
                    dt.Rows[row]["Bilgi"] = "---Harçama Detayları---";
                    var masrafHareketleri = ent.MasrafHareketleri.Where(x => x.ClosureID == c.ClosureID).Select(x => new { Adi = x.Aciklama, Tutar = x.Tutar }).ToArray();
                    for (int i = 0; i < 5; i++)
                    {
                        row++;
                        if (masrafHareketleri.Length > i)
                        {
                            dt.Rows[row]["Bilgi"] = masrafHareketleri[i].Adi;
                            dt.Rows[row][colName] = masrafHareketleri[i].Tutar;
                        }
                    }
                    row++;
                    dt.Rows[row]["Bilgi"] = "Harcamalar Toplam:";
                    dt.Rows[row][colName] = masrafFaturalari.Select(x => x.Tutar).Sum();
                    #endregion

                    #region En Son Bilgiler
                    double? acik = ent.AcikHesapHareketleri.Where(x => x.ClosureID == c.ClosureID).Select(x => (int?)x.KdvDahilTutar).Sum();
                    double aciktoplam = 0;
                    if (acik.HasValue)
                        aciktoplam = acik.Value;

                    row++;
                    dt.Rows[row]["Bilgi"] = "Cari Hesap:";
                    dt.Rows[row][colName] = aciktoplam;

                    double? ths = ent.CariTahsilatHareketleri.Where(x => x.ClosureID == c.ClosureID).Select(x => (int?)x.Tutar).Sum();
                    double tahsilat = 0;
                    if (ths.HasValue)
                        tahsilat = ths.Value;

                    row++;
                    dt.Rows[row]["Bilgi"] = "Tahsilat:";
                    dt.Rows[row][colName] = tahsilat;

                    row++;
                    dt.Rows[row]["Bilgi"] = "Z Toplam:";

                    var sonuc = (from z in ent.ZRaporlari
                                 where z.ClosureID == c.ClosureID
                                 group z by z into g
                                 select g.Sum(x => x.ZTutari + x.FaturaTutari)).FirstOrDefault();

                    dt.Rows[row][colName] = sonuc;
                    //dt.Rows[row][colName] = ent.ZRaporlari.Where(x => x.ClosureID == c.ClosureID).Select(x => x.ZTutari == null ? 0 : x.ZTutari + x.FaturaTutari ?? double.MinValue).Sum();

                    row++;
                    dt.Rows[row]["Bilgi"] = "Gerçekleşen Ciro:";
                    dt.Rows[row][colName] = (c.NakitToplam + c.KrediToplam + aciktoplam + c.HarcamalarToplam + c.MasrafFaturalarToplam + tahsilat);

                    row++;
                    dt.Rows[row]["Bilgi"] = "Kasa Farkı:";
                    dt.Rows[row][colName] = c.KasaFarki.ToString("n2");
                    #endregion
                }
            }

            List<DataRow> silRow = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i][0].ToString()))
                    silRow.Add(dt.Rows[i]);
            }

            for (int i = 0; i < silRow.Count; i++)
            {
                dt.Rows.Remove(silRow[i]);
            }

            frmViewer v = new frmViewer();
            v.DataSource = dt;
            v.Show();
        }

        private void dovizOku(string filename)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(filename);
            DataTable dt = new DataTable();
            dt.Columns.Add("Döviz Adı", typeof(string));
            dt.Columns.Add("Kur", typeof(string));
            for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
            {
                if (!string.IsNullOrEmpty(ds.Tables[1].Rows[i][5].ToString()))
                    dt.Rows.Add(ds.Tables[1].Rows[i][1], ds.Tables[1].Rows[i][5]);
            }
            dataGridView1.DataSource = dt;
            dataGridView1.Columns[0].Width = 300;
            ds.WriteXml(Application.StartupPath + "\\doviz.xml");
        }

        private void dövizGüncelleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dovizOku("http://www.tcmb.gov.tr/kurlar/today.xml");
        }

        private void cmbMagaza_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMagaza.SelectedIndex > -1)
            {
                Magaza mg = (Magaza)cmbMagaza.SelectedItem;
                Program.AktifDepoNo = mg.MagazaNo;
                Functions.SabitBilgileriYukle(Program.Db, new KasaEntity());
                KapanisKontrol(dteIslemTarihi.Value);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (lblUyari.Visible)
            {
                lblUyari.Visible = false;
            }
            else
            {
                lblUyari.Visible = true;
            }
        }

        private void dteIslemTarihi_ValueChanged(object sender, EventArgs e)
        {
            KapanisKontrol(dteIslemTarihi.Value);
        }

        private void kasiyerTanıtımToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmKasiyer frm = new frmKasiyer();
            frm.ShowDialog();
        }

        //private void dizaynToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    if (new frmSifre().ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        AllCashReport rp = new AllCashReport();
        //        using (FastReport.Report report = Printing.GetReport(ReportTypeOption.KasiyerOzetRaporu))
        //        {
        //            System.Windows.Forms.BindingSource binding = new System.Windows.Forms.BindingSource { DataSource = rp };
        //            report.RegisterData(binding, "Report", 10);
        //            report.GetDataSource("Report").Enabled = true;
        //            report.Prepare();
        //            report.Design();

        //            using (KasaEntity ent = new KasaEntity())
        //            {
        //                BelgeSablonu belge = (from b in ent.BelgeSablonlari where b.ReportType == (byte)ReportTypeOption.KasiyerOzetRaporu select b).FirstOrDefault();
        //                if (belge == null)
        //                {
        //                    ent.AddToBelgeSablonlari(new BelgeSablonu()
        //                    {
        //                        ReportType = (byte)ReportTypeOption.KasiyerOzetRaporu,
        //                        TemplateContent = File.ReadAllBytes(Printing.GetPath(ReportTypeOption.KasiyerOzetRaporu))
        //                    });
        //                }
        //                else
        //                {
        //                    belge.ReportType = (byte)ReportTypeOption.KasiyerOzetRaporu;
        //                    belge.TemplateContent = File.ReadAllBytes(Printing.GetPath(ReportTypeOption.KasiyerOzetRaporu));
        //                }
        //                ent.SaveChanges();
        //            }
        //        }
        //    }
        //}
    }
}
